
package at.fhj.ase.crypto.server.security;

import java.security.NoSuchAlgorithmException;

import javax.crypto.SecretKey;

import org.slf4j.Logger;

import at.fhj.ase.crypto.common.util.CryptoUtil;
import at.fhj.ase.crypto.common.util.LogUtil;

/**
 * Class responsible for all key operations like creating the session key and also sharing the key with other classes.<br>
 * As only one session key should exist, this class is implemented as a singleton pattern with the enum approach.
 * 
 * @author sfe | www.fh-joanneum.at | Practical Aspects of Cryptography
 * @throws IllegalStateException if there is a problem at key creation
 */
public enum SecurityController {
  INSTANCE;
  private final Logger logger = LogUtil.getLogger();

  /** The session key that is common to all chat participants and created at the very beginning */
  private SecretKey sessionKey;

  /*
   * TODO: save the keys into a (binary-)file
   */

  /**
   * Constructor initiating the keys.
   */
  private SecurityController() {
    try {
      initKeys();
    } catch (NoSuchAlgorithmException e) {
      logger.error("Could not instantiate keys", e);
      throw new IllegalStateException("Could not instantiate keys", e);
    }
  }

  /**
   * Initiates the keys of this instance.<br>
   * Currently only the session key is generated.
   */
  private void initKeys() throws NoSuchAlgorithmException {
    // generate session key
    sessionKey = CryptoUtil.createSecretKey(CryptoUtil.AES, 128);
    logger.debug("Successfully created session key");
  }

  /** @return the session key instance of this class */
  public SecretKey getSessionKey() {
    return sessionKey;
  }
}
